export const forEach = (arr, fn) => {
	if (!arr.length || !fn) return

	let i = -1

	let len = arr.length

	while (++i < len) {
		let item = arr[i]

		fn(item, i, arr)
	}
}

export const parseTime = (time, cFormat) => {
	if (time) {
		if (typeof time === 'string') {
			time = time.replace(/T/g, ' ')

			/* eslint-disable */
			time = time.replace(/\-/g, '/')
		}
		var datetime = new Date(time)
		var o = {
			'M+': datetime.getMonth() + 1, // month
			'd+': datetime.getDate(), // day
			'h+': datetime.getHours(), // hour
			'm+': datetime.getMinutes(), // minute
			's+': datetime.getSeconds(), // second
			'q+': Math.floor((datetime.getMonth() + 3) / 3), // quarter
			S: datetime.getMilliseconds() // millisecond
		}
		if (/(y+)/.test(cFormat)) {
			cFormat = cFormat.replace(RegExp.$1, (datetime.getFullYear() + '').substr(4 - RegExp.$1.length))
		}

		for (var k in o) {
			if (new RegExp('(' + k + ')').test(cFormat)) {
				cFormat = cFormat.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
			}
		}
		return cFormat
	} else {
		return time
	}
}
export const getDateTimeNow = () => {
	let myDate = new Date()
	let year = myDate.getFullYear() // 获取完整的年份(4位,1970-????)
	let month = myDate.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
	let date = myDate.getDate() // 获取当前日(1-31)
	let str = '星期' + '日一二三四五六'.charAt(new Date().getDay())
	return year + '年' + month + '月' + date + '日  ' + str
}

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @description 得到两个数组的交集, 两个数组的元素为数值或字符串
 */
export const getIntersection = (arr1, arr2) => {
	let len = Math.min(arr1.length, arr2.length)
	let i = -1
	let res = []
	while (++i < len) {
		const item = arr2[i]
		if (arr1.indexOf(item) > -1) res.push(item)
	}
	return res
}

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @description 得到两个数组的并集, 两个数组的元素为数值或字符串
 */
export const getUnion = (arr1, arr2) => {
	return Array.from(new Set([...arr1, ...arr2]))
}

/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
 */
export const hasOneOf = (targetarr, arr) => {
	return targetarr.some((_) => arr.indexOf(_) > -1)
}

/**
 * @param {String|Number} value 要验证的字符串或数值
 * @param {*} validList 用来验证的列表
 */
export function oneOf(value, validList) {
	for (let i = 0; i < validList.length; i++) {
		if (value === validList[i]) {
			return true
		}
	}
	return false
}

/**
 * @param {Number} timeStamp 判断时间戳格式是否是毫秒
 * @returns {Boolean}
 */
const isMillisecond = (timeStamp) => {
	const timeStr = String(timeStamp)
	return timeStr.length > 10
}

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} currentTime 当前时间时间戳
 * @returns {Boolean} 传入的时间戳是否早于当前时间戳
 */
const isEarly = (timeStamp, currentTime) => {
	return timeStamp < currentTime
}

/**
 * @param {Number} num 数值
 * @returns {String} 处理后的字符串
 * @description 如果传入的数值小于10，即位数只有1位，则在前面补充0
 */
const getHandledValue = (num) => {
	return num < 10 ? '0' + num : num
}

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} startType 要返回的时间字符串的格式类型，传入'year'则返回年开头的完整时间
 */
const getDate = (timeStamp, startType) => {
	const d = new Date(timeStamp * 1000)
	const year = d.getFullYear()
	const month = getHandledValue(d.getMonth() + 1)
	const date = getHandledValue(d.getDate())
	const hours = getHandledValue(d.getHours())
	const minutes = getHandledValue(d.getMinutes())
	const second = getHandledValue(d.getSeconds())
	let resStr = ''
	if (startType === 'year') resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second
	else resStr = month + '-' + date + ' ' + hours + ':' + minutes
	return resStr
}

/**
 * @param {String|Number} timeStamp 时间戳
 * @returns {String} 相对时间字符串
 */
export const getRelativeTime = (timeStamp) => {
	// 判断当前传入的时间戳是秒格式还是毫秒
	const IS_MILLISECOND = isMillisecond(timeStamp)
	// 如果是毫秒格式则转为秒格式
	if (IS_MILLISECOND) timeStamp = Math.floor((timeStamp /= 1000))
	// 传入的时间戳可以是数值或字符串类型，这里统一转为数值类型
	timeStamp = Number(timeStamp)
	// 获取当前时间时间戳
	const currentTime = Math.floor(Date.parse(new Date()) / 1000)
	// 判断传入时间戳是否早于当前时间戳
	const IS_EARLY = isEarly(timeStamp, currentTime)
	// 获取两个时间戳差值
	let diff = currentTime - timeStamp
	// 如果IS_EARLY为false则差值取反
	if (!IS_EARLY) diff = -diff
	let resStr = ''
	const dirStr = IS_EARLY ? '前' : '后'
	// 少于等于59秒
	if (diff <= 59) resStr = diff + '秒' + dirStr
	// 多于59秒，少于等于59分钟59秒
	else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr
	// 多于59分钟59秒，少于等于23小时59分钟59秒
	else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr
	// 多于23小时59分钟59秒，少于等于29天59分钟59秒
	else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr
	// 多于29天59分钟59秒，少于364天23小时59分钟59秒，且传入的时间戳早于当前
	else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp)
	else resStr = getDate(timeStamp, 'year')
	return resStr
}

/**
 * @returns {String} 当前浏览器名称
 */
export const getExplorer = () => {
	const ua = window.navigator.userAgent
	const isExplorer = (exp) => {
		return ua.indexOf(exp) > -1
	}
	if (isExplorer('MSIE')) return 'IE'
	else if (isExplorer('Firefox')) return 'Firefox'
	else if (isExplorer('Chrome')) return 'Chrome'
	else if (isExplorer('Opera')) return 'Opera'
	else if (isExplorer('Safari')) return 'Safari'
}

/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function () {
	if (document.addEventListener) {
		return function (element, event, handler) {
			if (element && event && handler) {
				element.addEventListener(event, handler, false)
			}
		}
	} else {
		return function (element, event, handler) {
			if (element && event && handler) {
				element.attachEvent('on' + event, handler)
			}
		}
	}
})()

/**
 * @description 解绑事件 off(element, event, handler)
 */
export const off = (function () {
	if (document.removeEventListener) {
		return function (element, event, handler) {
			if (element && event) {
				element.removeEventListener(event, handler, false)
			}
		}
	} else {
		return function (element, event, handler) {
			if (element && event) {
				element.detachEvent('on' + event, handler)
			}
		}
	}
})()

/**
 * 判断一个对象是否存在key，如果传入第二个参数key，则是判断这个obj对象是否存在key这个属性
 * 如果没有传入key这个参数，则判断obj对象是否有键值对
 */
export const hasKey = (obj, key) => {
	if (key) return key in obj
	else {
		let keysArr = Object.keys(obj)
		return keysArr.length
	}
}

/**
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 * @description 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 */
export const objEqual = (obj1, obj2) => {
	const keysArr1 = Object.keys(obj1)
	const keysArr2 = Object.keys(obj2)
	if (keysArr1.length !== keysArr2.length) return false
	else if (keysArr1.length === 0 && keysArr2.length === 0) return true
	/* eslint-disable-next-line */ else return !keysArr1.some((key) => obj1[key] !== obj2[key])
}
export const deepClone = (target) => {
	// 定义一个变量
	let result
	// 如果当前需要深拷贝的是一个对象的话
	if (typeof target === 'object') {
		// 如果是一个数组的话
		if (Array.isArray(target)) {
			result = [] // 将result赋值为一个数组，并且执行遍历
			for (let i in target) {
				// 递归克隆数组中的每一项
				result.push(deepClone(target[i]))
			}
			// 判断如果当前的值是null的话；直接赋值为null
		} else if (target === null) {
			result = null
			// 判断如果当前的值是一个RegExp对象的话，直接赋值
		} else if (target.constructor === RegExp) {
			result = target
		} else {
			// 否则是普通对象，直接for in循环，递归赋值对象的所有值
			result = {}
			for (let i in target) {
				result[i] = deepClone(target[i])
			}
		}
		// 如果不是对象的话，就是基本数据类型，那么直接赋值
	} else {
		result = target
	}
	// 返回最终结果
	return result
}
export const uuid = () => {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = (Math.random() * 16) | 0,
			v = c == 'x' ? r : (r & 0x3) | 0x8
		return v.toString(16)
	})
}
/*
 * 防抖
 */
export const debounce = (fn, delay = 500) => {
	// timer 是在闭包中的
	let timer = null
	return function () {
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			fn.apply(this, arguments)
			timer = null
		}, delay)
	}
}
/*
 *节流
 */
export const throttle = (fn, delay) => {
	let timer = null
	return function () {
		if (timer) {
			return
		}
		timer = setTimeout(() => {
			fn.apply(this, arguments)
			timer = null
		})
	}
}
/**
 * 导出Excel（下载也可以用这个方法）
 * @param {*} paramList 参数名列表
 * @param {*} dataList 参数值对象
 * @param {*} url 下载地址
 * @param {*} token 授权token
 */
export const ExportExcel = function (paramList, dataList, url, token) {
	var form = document.createElement('form')
	paramList.forEach((item) => {
		var element = document.createElement('input')
		element.value = dataList[item]
		element.name = item
		form.appendChild(element)
	})
	form.method = 'POST'
	form.action = url + '?token=' + token
	document.body.appendChild(form)
	form.submit()
	document.body.removeChild(form)
	return true
}

export const ExportExcelBlob = function (data, filename) {
	let blob = new Blob([data], { type: 'application/vnd.ms-excel' })
	// IE
	if (window.navigator && window.navigator.msSaveOrOpenBlob) {
		window.navigator.msSaveOrOpenBlob(blob, filename)
	} else {
		let url = window.URL.createObjectURL(blob)
		let downloadElement = document.createElement('a')
		downloadElement.href = url
		downloadElement.download = filename // 下载后文件名
		document.body.appendChild(downloadElement)
		downloadElement.click() // 点击下载
		document.body.removeChild(downloadElement) // 下载完成移除元素
		window.URL.revokeObjectURL(url) // 释放掉blob对象
	}
}
export const getLastMonth = function () {
	const now = new Date()
	const year = now.getFullYear() //getYear()+1900=getFullYear()
	let month = now.getMonth() + 1 //0-11表示1-12月
	let day = now.getDate()
	let dateObj = {}
	if (parseInt(month) < 10) {
		month = '0' + month
	}
	if (parseInt(day) < 10) {
		day = '0' + day
	}

	dateObj.now = year + '-' + month + '-' + day

	if (parseInt(month) == 1) {
		//如果是1月份，则取上一年的12月份
		dateObj.last = parseInt(year) - 1 + '-12-' + day
		return dateObj
	}

	var preSize = new Date(year, parseInt(month) - 1, 0).getDate() //上月总天数
	if (preSize < parseInt(day)) {
		//上月总天数<本月日期，比如3月的30日，在2月中没有30
		dateObj.last = year + '-' + month + '-01'
		return dateObj
	}

	if (parseInt(month) <= 10) {
		dateObj.last = year + '-0' + (parseInt(month) - 1) + '-' + day
		return dateObj
	} else {
		dateObj.last = year + '-' + (parseInt(month) - 1) + '-' + day
		return dateObj
	}
}
